import React from 'react';
import { Form, Input, Button, Alert, Row, Col } from 'antd';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { setTitle } from '../../utils/utils';
import styles from './login.css';
import loginBg from '../../assets/login-bg.png';
import logo from '../../assets/logo.png';
import { doLoginByUserNameAndPassword, getUserInfo } from '../../services/API';
import { setLoginToken, setUserInfo, clearLoginToken } from '../../utils/utils';
import { routerRedux } from 'dva/router';

const FormItem = Form.Item;

/**
 *  登录界面
 */
@connect(({ login, loading }) => ({
  login,
  //控制状态，绑定事件
  submitting: loading.effects['login/doLogin']
}))
@Form.create()
class LoginForm extends React.Component {
  state = {
    type: 'usernameAndPwd',
    loading: false
  };

  submitBtn = e => {
    e.preventDefault();
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        clearLoginToken();
        this.setState({
          loading: true
        });
        try {
          const resp = await doLoginByUserNameAndPassword(values);
          if (resp.code === 200) {
            setLoginToken(resp.token);
            const userInfoResp = await getUserInfo();
            if (userInfoResp.code === 200) {
              setUserInfo(userInfoResp.user);
              this.props.dispatch(routerRedux.push('/'));
              return;
            }
          } else {
            this.props.form.setFields({
              password: {
                errors: [
                  {
                    message: resp.msg,
                    field: 'password'
                  }
                ]
              }
            });
          }
          this.setState({
            loading: false
          });
        } catch (ex) {
          console.log('login error', ex);
          this.setState({
            loading: false
          });
        }
        // let username = values.username;
        // let password = values.password;
        // const { dispatch } = this.props;
        // const type = this.state.type;
        // dispatch({
        //   type: 'login/doLogin',
        //   payload: {
        //     ...values,
        //     // loginType: type,
        //   },
        // });
      }
    });
  };

  /**
   *  错误信息
   */
  renderMessage = content => {
    return <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />;
  };

  componentDidMount() {
    setTitle('Retailer platform');
  }

  /**
   * 点击其他方式登录
   * @param e 获取的点击的value
   */
  handleMenuClick = e => {
    console.log(e);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    // const { submitting, login } = this.props;
    const { loading } = this.state;

    return (
      <div className={styles.body}>
        <div className={styles.login}>
          <Row
            style={{
              height: '100%',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Col
              span={14}
              style={{
                height: '100%',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <img src={loginBg} alt="" className={styles.bg} />
            </Col>
            <Col
              span={10}
              style={{
                height: '100%',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                flexDirection: 'column'
              }}
            >
              <div className={styles.head}>
                <img className={styles.logo} src={logo} alt="" />
                <div className={styles.label}>Welcome to the retailer platform</div>
              </div>

              <Form onSubmit={this.submitBtn} style={{ width: '80%' }}>
                <FormItem>
                  {getFieldDecorator('username', {
                    rules: [{ required: true, message: 'Email cannot be empty!' }]
                  })(<Input id="username" placeholder="Email" className={'rc-input'} />)}
                </FormItem>

                <FormItem>
                  {getFieldDecorator('password', {
                    rules: [{ required: true, message: 'Password cannot be empty!' }]
                  })(
                    <Input.Password id="password" password="true" placeholder="Password" className={'rc-input-pwd'} />
                  )}
                </FormItem>
                <FormItem>
                  <div className={styles.forgot}>
                    <Link to="/forgotPassword">Forgot password</Link>{' '}
                  </div>
                  <Button
                    loading={loading}
                    block
                    style={{ borderBottomRightRadius: 0, background: '#333', border: 0, borderTopRightRadius: 0 }}
                    type="primary"
                    htmlType="submit"
                  >
                    Sign in
                  </Button>
                </FormItem>
              </Form>
            </Col>
          </Row>
        </div>
      </div>
    );
  }
}
export default LoginForm;
